package com.fzy.springsecurity2.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.security.core.GrantedAuthority;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author fzy
 * @version 1.0
 * 创建时间：2024-10-13 13:19
 */

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MyJacksonTypeHandler extends BaseTypeHandler<List<GrantedAuthority>> {

    static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<GrantedAuthority> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, objectMapper.writeValueAsString(parameter));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GrantedAuthority> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String JavaType = rs.getString(columnName);
        try {
            return objectMapper.readValue(JavaType, specificType());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GrantedAuthority> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String JavaType = rs.getString(columnIndex);
        try {
            return objectMapper.readValue(JavaType,  specificType());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<GrantedAuthority> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String JavaType = cs.getString(columnIndex);
        try {
            return objectMapper.readValue(JavaType,  specificType());
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    // 可以通过重写此方法来指定特定的类型
    protected TypeReference<List<GrantedAuthority>> specificType() {
        return new TypeReference<>() {
        };
    }

}
